package com.atguigu.gulimall.cart.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.TypeReference;
import com.atguigu.common.utils.R;
import com.atguigu.gulimall.cart.feign.ProductFeignService;
import com.atguigu.gulimall.cart.interceptor.CartInterceptor;
import com.atguigu.gulimall.cart.service.CartService;
import com.atguigu.gulimall.cart.vo.Cart;
import com.atguigu.gulimall.cart.vo.CartItem;
import com.atguigu.gulimall.cart.vo.SkuInfoVo;
import com.atguigu.gulimall.cart.vo.UserInfoTo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import java.util.List;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.stream.Collectors;

@Service
public class CartServiceImpl implements CartService {

    @Autowired
    StringRedisTemplate redisTemplate;

    @Autowired
    ProductFeignService productFeignService;

    @Autowired
    ThreadPoolExecutor pool;

    private final String CART_PREFIX = "gulimall:cart:";

    @Override
    public CartItem addToCart(Long skuId, Integer num) {
        BoundHashOperations cartOps = getCartOps();
        // 2、商品添加到购物车
        CartItem cartItem = new CartItem();

        String res = (String) cartOps.get(skuId.toString());
        if (!StringUtils.isEmpty(res)) {
            // 有商品
            CartItem item = JSON.parseObject(res, CartItem.class);
            Integer count = item.getCount();
            item.setCount(count + num);
            cartOps.put(skuId.toString(), JSON.toJSONString(item));
            return item;
        }

        //查询 当前要添加商品的信息
        CompletableFuture<Void> getSkuInfoTask = CompletableFuture.runAsync(() -> {
            R info = productFeignService.getSkuinfo(skuId);
            SkuInfoVo skuInfo = info.getData("data", new TypeReference<SkuInfoVo>() {
            });

            cartItem.setSkuId(skuId);
            cartItem.setCount(num);
            cartItem.setImg(skuInfo.getSkuDefaultImg());
            cartItem.setTitle(skuInfo.getSkuTitle());
            cartItem.setPrice(skuInfo.getPrice());
        }, pool);

        CompletableFuture<Void> getSkuSaleAttrValues = CompletableFuture.runAsync(() -> {
            List<String> attrValues = productFeignService.getSkuSaleAttrValues(skuId);
            // 3、远程查询sku的组合信息
            cartItem.setSkuAttr(attrValues);
        }, pool);

        try {
            CompletableFuture.allOf(getSkuInfoTask, getSkuSaleAttrValues).get();
        } catch (Exception e) {
            e.printStackTrace();
        }

        cartOps.put(skuId.toString(), JSON.toJSONString(cartItem));
        return cartItem;
    }

    @Override
    public CartItem getCartItem(Long skuId) {
        BoundHashOperations cartOps = getCartOps();

        String o = (String) cartOps.get(skuId.toString());
        CartItem cartItem = JSON.parseObject(o, CartItem.class);
        return cartItem;
    }

    @Override
    public Cart getCart() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
        Cart cart = new Cart();

        if (userInfoTo.getUserId() != null) {
            // 1、登录
            String cartKeys = CART_PREFIX + userInfoTo.getUserId();
            // 2、如果临时购物车的数据还没有进行合并
            String tempCartKeys = CART_PREFIX + userInfoTo.getUserKey();
            List<CartItem> tempCartItems = getCartItems(tempCartKeys);
            if (tempCartItems != null) {
                // 临时购物车有数据需要合并
                for (CartItem item : tempCartItems) {
                    addToCart(item.getSkuId(), item.getCount());
                }
                // 清除临时购物车
                clearCart(tempCartKeys);
            }
            //  3、获取登录后的购物车的数据【包含所有购物车数据】
            List<CartItem> cartItems = getCartItems(cartKeys);
            cart.setItems(cartItems);
        } else {
            // 2、未登录
            String userKey = CART_PREFIX + userInfoTo.getUserKey();
            // 获取临时购物车的所有购物项
            List<CartItem> cartItems = getCartItems(userKey);
            cart.setItems(cartItems);
        }

        return cart;
    }

    @Override
    public void clearCart(String cartKey) {
        redisTemplate.delete(cartKey);
    }

    @Override
    public void checkItem(Long skuId, Integer check) {
        BoundHashOperations cartOps = getCartOps();
        CartItem item = getCartItem(skuId);
        if (check == 1) {
            item.setCheck(true);
        } else {
            item.setCheck(false);
        }
        cartOps.put(skuId.toString(), JSON.toJSONString(item));
    }

    @Override
    public void countItem(Long skuId, Integer num) {
        BoundHashOperations cartOps = getCartOps();
        CartItem item = getCartItem(skuId);
        item.setCount(num);
        cartOps.put(skuId.toString(), JSON.toJSONString(item));
    }

    @Override
    public void deleteItem(Long skuId) {
        BoundHashOperations cartOps = getCartOps();
        cartOps.delete(skuId.toString());
    }

    @Override
    public List<CartItem> getUserCartItems() {
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();
       if ( userInfoTo.getUserId() == null){
           return null;
       }else {
           String cartKeys = CART_PREFIX + userInfoTo.getUserId();
           List<CartItem> cartItems = getCartItems(cartKeys);
           // 获取被选中的购物项
           List<CartItem> items = cartItems.stream()
                   .filter(item -> item.getCheck())
                   .map(item -> {
                       // 更新为最新价格
                       R skuinfo = productFeignService.getSkuinfo(item.getSkuId());
                       SkuInfoVo data = skuinfo.getData("data", new TypeReference<SkuInfoVo>() {
                       });
                       item.setPrice(data.getPrice());
                       return item;
                   })
                   .collect(Collectors.toList());
           return items;
       }
    }


    private List<CartItem> getCartItems(String userKey) {
        BoundHashOperations<String, Object, Object> ops = redisTemplate.boundHashOps(userKey);
        List<Object> values = ops.values();
        if (values != null && values.size() > 0) {
            List<CartItem> cartItems = values.stream().map((obj) -> {
                String str = (String) obj;
                CartItem cartItem = JSON.parseObject(str, CartItem.class);
                return cartItem;
            }).collect(Collectors.toList());
            return cartItems;
        }
        return null;
    }


    private BoundHashOperations getCartOps() {
        // 得到当前的用户信息
        UserInfoTo userInfoTo = CartInterceptor.threadLocal.get();

        String cartKey = "";
        if (userInfoTo.getUserId() != null) {
            cartKey = CART_PREFIX + userInfoTo.getUserId();
        } else {
            cartKey = CART_PREFIX + userInfoTo.getUserKey();
        }

        BoundHashOperations<String, Object, Object> operations = redisTemplate.boundHashOps(cartKey);
        return operations;
    }


}
